<template>
    <el-main id="app"
        :style="{ background: 'url(' + backgroundImage + ') center center no-repeat', backgroundSize: 'cover' }">
        <div :style="{
            width: '100%',
            backgroundColor: fontBackColor, height: '100px', fontSize: titleFontSize, display: 'flex', justifyContent: 'center', alignItems: 'center', color: titleFontColor, fontSize: 'xx-large'
        }">
            <marquee :direction="textAnimation">{{ welcomeBanner }}</marquee>
        </div>
        <div
            :style="{ width: 'calc(100%-' + 2 + 'px)', flex: '1', border: borderWidth + 'px solid ' + backBorderColor, background: 'url(' + borderBackground + ') no-repeat 0 0 / 100% 100%' }">
            <transition leave-active-class="animate__animated animate__bounceOutLeft"
                :enter-active-class="'animate__animated '+toggleAnimation" mode="out-in">
                <div id="canvas" v-show="showCanvas"
                    style=" width: 100%;height: 100%;">
                    <video style="display: none;" id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight"
                        autoPlay></video>
                    <canvas style="display: none;" id="canvasCamera" class="canvas" :width="videoWidth"
                        :height="videoHeight"></canvas>
                    <!-- <transition name="el-zoom-in-center" style="width: 100%;height: 100%;background-color: aqua;"></transition> -->
                </div>
            </transition>
        </div>

    </el-main>
</template>
  
<script>
import 'animate.css';
import request from "../axios/request";
export default {
    data() {
        return {
            backgroundImage: null,
            styleIds: [],
            timeInterval: null,
            timer: null,
            styleIndex: 0,
            newNodeNum: null,
            itemImage: null,
            showCanvas: true,
            welcomeBanner: null,
            titleFontSize: null,
            fontBackColor: null,
            backBorderColor: null,
            borderWidth: null,
            borderBackground: null,
            borderDisplayStyle: null,
            displayArea: null,
            titleFontColor: null,
            textAnimation: null,
            toggleAnimation:null,

            os: false,//控制摄像头开关
            thisVideo: null,
            thisContext: null,
            thisCancas: null,
            imgSrc: '',
            videoWidth: 500,
            videoHeight: 400,

        }
    },
    methods: {
        async getDisplayInfo() {
            //  获取display信息
            let resOfGettingDisplayInfo = await request({
                url: "/api/display/getDisplayInfo",
                method: "GET"
            });
            let result = resOfGettingDisplayInfo.data.data
            if (result != null) {
                this.backgroundImage = result.backgroundImageUrl
                this.timeInterval = result.timeInterval
                // this.itemImage = result.noBackground
                this.welcomeBanner = result.welcomeBanner
                this.titleFontSize = result.fontSize
                this.fontBackColor = result.fontBackColor
                this.backBorderColor = result.backBorderColor
                this.borderWidth = result.borderWidth
                this.borderBackground = result.borderBackground
                this.titleFontColor = result.fontColor
                this.textAnimation = result.textAnimation
                this.toggleAnimation=result.toggleAnimation
            }
        },
        changeStyle() {
            this.showCanvas = false
            this.photographBtn()
            this.cleanCanvas()
            var that = this
            request({
                url: "/api/style/getStyleInfo/" + this.styleIds[this.styleIndex],
                method: "GET"
            }).then(res => {
                that.styleIndex++
                if (that.styleIndex == that.styleIds.length) {
                    that.styleIndex = 0
                    console.log("完成一轮循环");
                }
                var windows = res.data.data.list
                that.newNodeNum = res.data.data.newNodeNum
                for (let index = 0; index < windows.length; index++) {
                    that.drawWindow(windows[index])
                }
                that.showCanvas = true
            })
        },
        drawWindow(myWindow, type) {
            var canvas = document.getElementById("canvas");
            var box = document.createElement("div")
            box.id = myWindow.windowId
            var width = null
            var height = null
            var left = null
            var top = null
            if (type == null) {
                width = Math.floor(canvas.getBoundingClientRect().width * (Number(myWindow.width.split("%")[0]) / 100))
                height = Math.floor(canvas.getBoundingClientRect().height * (Number(myWindow.height.split("%")[0]) / 100))
                left = Math.floor(canvas.getBoundingClientRect().width * (Number(myWindow.left.split("%")[0]) / 100) + canvas.offsetLeft)
                top = Math.floor(canvas.getBoundingClientRect().height * (Number(myWindow.top.split("%")[0]) / 100) + canvas.offsetTop)
            } else if (type == 'absolute') {
                width = myWindow.width
                height = myWindow.height
                left = Number(myWindow.left) + canvas.offsetLeft
                top = Number(myWindow.top) + canvas.offsetTop
            }
            box.style = "position: absolute;width: " + width + "px;height: " + height + "px;display: flex;justify-content: center;align-items: center;border:dashed 1px black;background: url(" + this.itemImage + ") center center no-repeat;background-size:  cover;"
            box.style.left = left + 'px'
            box.style.top = top + 'px'
            // box.classList.add("animate__animated animate__bounce")
            canvas.insertBefore(box, null);
        },
        cleanCanvas() {
            for (let index = 0; index <= this.newNodeNum; index++) {
                var curWin = document.getElementById("editBox" + index)
                if (curWin == null) {
                    continue
                }
                curWin.remove()
            }
        },
        async getAllStyleId() {
            let resOfGettingOldStyleInfo = await request({
                url: "/api/style/getAllStyleId",
                method: "GET"
            });
            this.styleIds = resOfGettingOldStyleInfo.data.data
            this.timer = setInterval(this.changeStyle, (this.timeInterval < 2 || this.timeInterval == null ? 5 * 1000 : this.timeInterval * 1000))
        },
        // 调用摄像头权限
        openCamera() {
            //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
            this.$nextTick(() => {
                const _this = this;
                this.os = false;//切换成关闭摄像头
                this.thisCancas = document.getElementById('canvasCamera');
                this.thisContext = this.thisCancas.getContext('2d');
                this.thisVideo = document.getElementById('videoCamera');
                // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
                if (navigator.mediaDevices === undefined) {
                    console.log("属于旧版本浏览器");
                    navigator.mediaDevices = {}
                }
                // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
                // 使用getUserMedia，因为它会覆盖现有的属性。
                // 这里，如果缺少getUserMedia属性，就添加它。
                if (navigator.mediaDevices.getUserMedia === undefined) {
                    console.log("缺少getUserMedia属性");
                    navigator.mediaDevices.getUserMedia = function (constraints) {
                        // 首先获取现存的getUserMedia(如果存在)
                        let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
                        // 有些浏览器不支持，会返回错误信息
                        // 保持接口一致
                        if (!getUserMedia) {
                            console.log('getUserMedia is not implemented in this browser');
                            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
                        }
                        // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
                        return new Promise(function (resolve, reject) {
                            console.log('使用Promise将调用包装到旧 的navigator');
                            getUserMedia.call(navigator, constraints, resolve, reject)
                        })
                    }
                }
                console.log("未缺少getUserMedia属性");
                const constraints = {
                    audio: false,
                    video: { width: _this.videoWidth, height: _this.videoHeight, transform: 'scaleX(-1)' }
                };
                console.log("执行getUserMedia");
                navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                    console.log("执行getUserMedia方法体");
                    // 旧的浏览器可能没有srcObject
                    if ('srcObject' in _this.thisVideo) {
                        console.log("存在srcObject");
                        _this.thisVideo.srcObject = stream
                    } else {
                        // 避免在新的浏览器中使用它，因为它正在被弃用。
                        console.log("避免在新的浏览器中使用它");
                        _this.thisVideo.src = window.URL.createObjectURL(stream)
                    }
                    console.log("启动摄像头外设");
                    _this.thisVideo.onloadedmetadata = function (e) {
                        _this.thisVideo.play()
                    }
                }).catch(err => {
                    this.$message({
                        message: '没有开启摄像头权限或浏览器版本不兼容',
                        type: 'warning'
                    });
                });
            });
        },
        //拍照按钮
        photographBtn() {
            // 点击，canvas画图
            this.thisContext.drawImage(this.thisVideo, 0, 0, this.videoWidth, this.videoHeight);
            // 获取图片base64链接
            this.itemImage = this.thisCancas.toDataURL('image/png');
            // var fileURL=
            // console.log(this.itemImage);
        },
        //关闭摄像头
        stopCamera() {
            if (this.thisVideo && this.thisVideo !== null) {
                this.thisVideo.srcObject.getTracks()[0].stop();
                this.os = true;//切换成打开摄像头
            }
        },
    },

    async created() {
        this.getAllStyleId()
        this.getDisplayInfo()
        this.openCamera()
    },
    beforeDestroy() {
        clearInterval(this.timer)
        this.stopCamera()
    }
}
</script>
  
<style scoped>
#app {
    width: 100%;
    position: absolute;
    height: 100%;
    left: 0;
    top: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    padding: 10px;
    overflow: hidden;
}

body {
    margin: 0;
    padding: 0;
}
</style>
  